//
//  DXMainViewController.swift
//  DXWeibo00
//
//  Created by xiongdexi on 16/4/6.
//  Copyright © 2016年 DXSmile. All rights reserved.
//

import UIKit

class DXMainViewController: UITabBarController {
    
    
    @objc private func clickComposedButton() {
        print("点了中间的撰写按钮")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加所有的子控制器
        addChildViewControllers()
        
        // 添加中间的撰写按钮
        setupComposeButton()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composedButton)
        
    }
    
    // MARK: - 懒加载控件
    // 使用的是自己定义的button的便利构造函数
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}


// MARK: - 设置页面
extension DXMainViewController {
    
    /// 设置中间的撰写按钮
    private func setupComposeButton() {
    
        // 1. 为tabBar添加按钮
        tabBar.addSubview(composedButton)
        
        // 2. 调整按钮
        let count = childViewControllers.count
        // 让按钮宽一点点，能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        // 3. 添加监听方法
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
        
    }
    


    /// 添加所有子控制器
    private func addChildViewControllers() {
        
        // 设置 tintColor － 图片渲染颜色
        // 性能提升的技巧 - 如果能够用颜色解决，就不建议使用图片
        tabBar.tintColor = UIColor.orangeColor()
    
        addChildViewController(DXHomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(DXMessageViewController(), title: "消息", imageName: "tabbar_message_center")
        // 中间的按钮
        addChildViewController(UIViewController())
        
        addChildViewController(DXDiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(DXProfileViewController(), title: "我", imageName: "tabbar_profile")

    }
    
    
    /// 添加一个控制器
    ///
    /// - parameter childController: 控制器
    /// - parameter title:           控制器title
    /// - parameter imageName:       tabBarItem的image
    private func addChildViewController(childController: UIViewController, title: String, imageName:String) {
        
        childController.title = title
        
        childController.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: childController)
    
        addChildViewController(nav)
    }
    
}
